import React from 'react'
import { connect } from 'react-redux'
import {messages} from "share/common";
import menuRoute from 'routes/menuRoute'
import { Button, Table, Form, Badge, Input, message, Modal, Switch} from 'antd';
const FormItem = Form.Item;
import { LanguageInput } from 'components/index'
import CityGroupService from 'containers/setting/city-group/city-group.service';
import 'styles/setting/city-group/city-group-allot-company.scss';
const codeError = [
  "6035005",
  "6057001",
  "6057002",
  "6057003",
  "6057004",
  "6057005",
  "6057006",
];

class CityGroupSlideFrame extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      record: {
        levelName: '',
        comment: '',
        i18n: {}//包含名称,描述
      },
      loading: false,
      disabled: true,
    }
  };

  //获取数据
  componentWillMount() {
    this.setState({
      record: this.props.params,
    })
  }

//状态变化时,获取默认值数据
  componentWillReceiveProps (nextProps){
    this.setState({
      record: nextProps.params,
    })
  };

  //点击模态框的确认
  onModalOK = (e) => {
    e.preventDefault();
    const {record} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      values.deleted = !values.deleted;
      if(!err){
        this.setState({
          loading: true,
        });
        if(JSON.stringify(record) === '{}'){
          let param = Object.assign({}, values);
          CityGroupService.addCityGroup(param).then(res => {
            this.setState({
              loading: false,
              disabled: true,
            });
            this.props.form.resetFields();
            this.props.close(true);
          }).catch(err => {
            if(codeError.indexOf(err.response.data.errorCode) !== -1){
              this.setState({
                disabled: false,
                loading: false,
              });
            }else{
              this.setState({
                disabled: true,
                loading: false,
              });
            }
          })
        }else{
          let param = Object.assign(record, values)
          CityGroupService.editCityGroup(param).then(res => {
            this.setState({
              loading: false,
              disabled: true,
            });
            this.props.form.resetFields();
            this.props.close(true);
          }).catch(err => {
            if(codeError.indexOf(err.response.data.errorCode) !== -1){
              this.setState({
                disabled: false,
                loading: false,
              });
            }else{
              this.setState({
                disabled: true,
                loading: false,
              });
            }
          })
        }
      }
    })
  };

  onCancel = () => {
    this.props.close();
    this.props.form.resetFields();
    this.setState({
      disabled: true,
      loading: false,
    });
  };

  onSwitchChange = () => {
    if(this.props.form.getFieldValue('deleted')){
      this.confirmDisable();
    }
  };

  //适用范围选择部分时
  confirmDisable = () => {
    let that = this;
    Modal.confirm({
      title: messages('setting.key1483')/*禁用后，城市组中的城市将被清空， 确认禁用*/,
      okText: messages('setting.key1484')/*确认*/,
      cancelText: messages('setting.key1080')/*取消*/,
      iconType: 'info-circle',
      onOk() {
        that.isSwitchChange(false);
      },
      onCancel() {
        that.isSwitchChange(true);
      },
    });
  };

  isSwitchChange = (bool) => {
    this.props.form.setFieldsValue({deleted: bool})
  };

  //子应用名称：多语言
  i18nAppNameChange = (name, i18nName) => {
    const record = this.state.record;
    record.levelName = name;
    if (!record.i18n) {
      record.i18n = {};
    }
    record.i18n.levelName = i18nName;
  };

  //子应用描述：多语言
  i18nAppCommentChange = (name, i18nName) => {
    const record = this.state.record;
    record.comment = name;
    if (!record.i18n) {
      record.i18n = {};
    }
    record.i18n.comment = i18nName;
  };

  render () {
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: { span:6 },
      wrapperCol: { span:16 }
    };
    const {record, disabled} = this.state;
    return (
      <div>
        <Form onSubmit={this.onModalOK}>
          <FormItem label={messages('common.column.status'/*状态*/)} {...formItemLayout}>
            {getFieldDecorator('deleted',{
              initialValue: JSON.stringify(record) === '{}' ? true : !record.deleted,
              valuePropName: "checked",
            })
            (<Switch onChange={this.onSwitchChange}/>)
            }
          </FormItem>
          <FormItem label={<span><span style={{color: 'red'}}>*</span>&nbsp;{messages('setting.key181'/*名称*/)}</span>}
                    {...formItemLayout}>
            <LanguageInput
              key={1}
              isEdit={record.id}
              name={record.levelName}
              i18nName={record.i18n && record.i18n.levelName ? record.i18n.levelName : null}
              placeholder={messages('setting.key183'/*请输入,最多50个字符*/)}
              nameChange={this.i18nAppNameChange}/>
          </FormItem>
          <FormItem label={messages('setting.key184'/*编码*/)} {...formItemLayout}>
            {getFieldDecorator('code',{
              initialValue: JSON.stringify(record) === '{}' ? '' : record.code,
              rules: [{
                required: true,
                message: messages('setting.key185'/*编码不能为空*/)
              }]
            })
            (<Input placeholder={messages('common.please.enter')/* 请输入 */}
                    disabled={!!(JSON.stringify(record) !== '{}' && record.code && disabled)}/>)
            }
          </FormItem>
          <FormItem label={messages('setting.key186'/*描述*/)} {...formItemLayout}>
            <LanguageInput
              key={2}
              isEdit={record.id}
              name={record.comment}
              i18nName={record.i18n && record.i18n.comment ? record.i18n.comment : null}
              placeholder={messages('setting.key187'/*请输入,最多150个字符*/)}
              nameChange={this.i18nAppCommentChange}
            />
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={this.state.loading}>{messages('common.save')}</Button>
            <Button onClick={this.onCancel}>{messages('common.cancel')}</Button>
          </div>
        </Form>
      </div>
    )
  }
  }

function mapStateToProps(state) {
  return {
  }
}

const wrappedCityGroupSlide = Form.create()(CityGroupSlideFrame);
export default connect(mapStateToProps)(wrappedCityGroupSlide);
